<template>
	<view class="wm">
		<view class="form">
			<uni-forms ref="form"  :modelValue="FormData">
				<uni-forms-item label="民族:" name="nation" required>
					<uni-data-select
						v-model="FormData.nation"
						:localdata="nations"
						@change="change"
					></uni-data-select>
				</uni-forms-item>
				<button  @click="save" class="savebtn">保存</button>
			</uni-forms>
			
		</view>
	</view>
</template>

<script>
	import {mapState,mapMutations} from "vuex"
	export default {
		data() {
			return {
				FormData:{
					nation:""
				},
				nations:[]
			}
		},
		computed:{
			...mapState("m_user",["userInfo","id"]),
		},
		onLoad(){
			this.init_data()
		},
		methods: {
			...mapMutations("m_user",['updateUserInfo']),
			/**
			 * 初始化数据
			 */
			async init_data(){
				//查询数据库中的民族，把获取回来的数据保存到当前的nations数组中
				const {data:res} = await uni.$http.post("Users/nation")
				if(res.meta.status == 0) return uni.$showMsg("查询民族失败")
				let nation = []
				for( let index in res.data){
					nation[index] = {
						"text":res.data[index]['name'],
						"value":res.data[index]['name']
					}
				}
				this.nations = nation
				//初始化民族
				this.FormData.nation = this.userInfo.nation
			},
			change(){
				
			},
			/**
			 * 保存
			 */
			save(){
				uni.showLoading()
				this.$refs.form.validate().then(async (res) => {
					//组织要修改的数据
					let $query = {
						"token":this.userInfo.token,
						"id":this.userInfo.id,
						"nation":res.nation,
					}
					//请求数据接口修改数据
					const {data:result} = await uni.$http.post("Users/updateUserInfo",$query)
					if(result.meta.status == 0) return uni.$showMsg(result.meta.msg);
					//将新的token数据保存到返回的数据中，重新保存到storage中
					result.data['token'] = this.userInfo.token
					//修改成功之后更新storage中的用户信息
					this.updateUserInfo(result.data);
					uni.hideLoading()
					uni.$showMsg(result.meta.msg);
					//返回管理页面
					setTimeout(()=>{
						uni.navigateBac({
							url:"/subpkg/manage/manage"
						})
					},1500);
				}).catch(err => {
					uni.hideLoading()
					uni.$showMsg(err[0].errorMessage);
				})
			},
		}
		
	}
</script>

<style lang="scss">
.form{
	background-color:#fff;
	margin-top:30rpx;
	padding:20rpx;
	border-radius: 15rpx;
}
.savebtn{
	background:linear-gradient(to  right,#feb27a,#ff7d5d);
	color:#fff;
	height: 35px;
	border:0;
	line-height: 35px;
	&:active{
		background:linear-gradient(to  right,#eba470,#e97055);
	}
}
.sex{
	height: 35px;
	line-height: 35px;
	display: flex;
	align-items: center;
}
</style>
